package com.example.smartgreenhouse.controller;

import com.example.smartgreenhouse.entity.DeviceCurrent;
import com.example.smartgreenhouse.entity.PumpOperationLog;
import com.example.smartgreenhouse.exception.BusinessException;
import com.example.smartgreenhouse.service.DeviceCurrentService;
import com.example.smartgreenhouse.service.FanService;
import com.example.smartgreenhouse.annotation.JwtToken;
import com.example.smartgreenhouse.annotation.Limit;
import com.example.smartgreenhouse.entity.PumpOperationLog;
import com.example.smartgreenhouse.exception.BusinessException;
import com.example.smartgreenhouse.service.PumpService;
import com.example.smartgreenhouse.utils.ResponseWrapper;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/gsas/api/v1/device/water_pump")
@RequiredArgsConstructor
public class PumpController {

    @Autowired
    private final PumpService pumpService;

    @Autowired
    private final DeviceCurrentService deviceCurrentService;

    @PostMapping("/auto_control")
    @JwtToken
    @Limit(
            key = "setWaterPumpAutoControl",                          // 限流标识（通常作为Key）
            permitsPerSecond = 3.0,                 // 每秒许可数
            timeout = 1000,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<?> autoControlPump(@RequestBody @Valid AutoPumpControlRequest request){
        try {
            // 处理默认值
            Long pumpId = request.getPumpId() != null ? request.getPumpId() : 2L;
            Long greenhouseId = request.getGreenhouseId() != null ? request.getGreenhouseId() : 1L;
            Long operatorId = request.getOperatorId()!=null ? request.getOperatorId() : 1L;
            Integer action = request.getAction();

            Map<String,Object> operationLog = pumpService.setPumpAuto(pumpId,greenhouseId,operatorId,action);
            return ResponseEntity.ok(operationLog);
        } catch (BusinessException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }

    @PostMapping("/control")
    @JwtToken
    @Limit(
            key = "controlWaterPump",                          // 限流标识（通常作为Key）
            permitsPerSecond = 3.0,                 // 每秒许可数
            timeout = 1000,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<ResponseWrapper<?>> controlPump(
            @RequestBody @Valid PumpControlRequest request) {
        try {
            // 处理默认值
            Long pumpId = request.getPumpId() != null ? request.getPumpId() : 2L;
            Long greenhouseId = request.getGreenhouseId() != null ? request.getGreenhouseId() : 1L;
            Long operatorId = request.getOperatorId()!=null ? request.getOperatorId() : 1L;
            PumpOperationLog operationLog = pumpService.controlPump(
                    pumpId,
                    greenhouseId,
                    request.getLevel(),
                    operatorId
            );

            return ResponseEntity.ok(ResponseWrapper.success("设置水泵挡位成功",operationLog));
        } catch (BusinessException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }

    @GetMapping("/current")
    @Limit(
            key = "Pump_current",                          // 限流标识（通常作为Key）
            permitsPerSecond = 40.0 / 60.0,                 // 每秒许可数
            timeout = 500,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<ResponseWrapper<?>> getPumpCurrentStatus(
            @RequestParam Long pumpId) {
        try {
            DeviceCurrent pumpCurrent = deviceCurrentService.getDeviceStatus("water_pump", pumpId);
            return ResponseEntity.ok(ResponseWrapper.success(
                    pumpId + "号水泵的状态获取成功", pumpCurrent));
        } catch (BusinessException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }


    @GetMapping("/history/{pumpId}")
    @JwtToken
    @Limit(
            key = "getWaterPumpHistoryOperation",                          // 限流标识（通常作为Key）
            permitsPerSecond = 3.0 ,                 // 每秒许可数
            timeout = 1000,                         // 尝试获取令牌的等待时间（毫秒）
            limitType = Limit.LimitType.IP,        // 限流策略（按IP限流）
            msg = "请求过于频繁，请稍后再试."      // 超限后的提示信息
    )
    public ResponseEntity<ResponseWrapper<?>> getPumpHistory(
            @PathVariable Long pumpId) {
        try{
            List<PumpOperationLog> history = pumpService.getPumpHistory(pumpId);
            return ResponseEntity.ok(ResponseWrapper.success("查询水泵操作历史记录成功", history));
        } catch (BusinessException e) {
            return ResponseEntity.badRequest()
                    .body(ResponseWrapper.badRequest(e.getMessage()));
        }
    }

    @Data
    public static class PumpControlRequest {
        //@NotNull(message = "水泵ID不能为空")
        private Long pumpId;

        //@NotNull(message = "大棚ID不能为空")
        private Long greenhouseId;

        @NotNull(message = "操作档位不能为空")
//        @Min(value = 0, message = "档位最小值为0")
//        @Max(value = 3, message = "档位最大值为3")
        private String level;

        //@NotBlank(message = "操作人不能为空")
        private Long operatorId;

        private Boolean is_auto;
    }
    @Data
    public static class AutoPumpControlRequest {
        private Long pumpId;
        private Long greenhouseId;
        @NotNull(message = "操作动作不能为空")
        private Integer action; // 0 关闭自动灌溉，1 开启自动灌溉
        private Long operatorId;
    }
}